package com.atwulidun.controller;

import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.protocol.http.ntlm.NTLMAuthenticationCallback;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/user")
public class UserController {
    // 解析传过来的JWT
    // 测试方法：
    // 1.在postman地址栏中输：http://localhost:8080/user/getCurrentUser
    // 2.不选则Authorization
    // 3.在Headers中输：Authorization bearer空格accessToken
    // 4.输出：
    // {
    //    "user_name": "admin",
    //    "scope": [
    //        "all"
    //    ],
    //    "exp": 1617083166,
    //    "authorities": [
    //        "admin"
    //    ],
    //    "jti": "ddab211a-891a-4302-b751-68b9de19f205",
    //    "client_id": "admin",
    //    "enhance": "enhance info"
    //}
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {
        String head = request.getHeader("Authorization");
        // head.indexOf("bearer")为"bearer"在head中第一次出现的位置
        // head.substring(head.indexOf("bearer") + 7)指的是从"bearer"在head中第一次出现的位置
        // 的后面的第七位开始(bearer6位，加上空格7位)一直截取到字符串结束
        String token = head.substring(head.indexOf("bearer") + 7);
        return Jwts.parser()
                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }
}
